package virtorina.server.rpc;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;

import virtorina.client.admin.dto.LabelDTO;
import virtorina.client.room.dto.InfoDTO;
import virtorina.client.room.rpc.GWTInsertQuestions;
import virtorina.client.room.rpc.GWTService4Room;
import virtorina.server.domain.Label;
import virtorina.server.domain.Question;
import virtorina.server.domain.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GWTInsertQuestionsImpl extends RemoteServiceServlet implements
		GWTInsertQuestions {

	@Override
	public Long insertQuestions(Long id, String question, LinkedList<String> answers,
			LinkedHashSet<String> labels, Integer type, String provider,
			Integer time) {
		Long UserID = (Long) this.getThreadLocalRequest().getSession()
				.getAttribute("user");
		Question q = new Question(question, answers, UserID, type, provider,
				time);
		if (!id.equals(-1L)){
			System.out.println("test2");
			q.setID(id);
		}
		return Question.addQuestionAndLabels(q, labels);
	}

	@Override
	public LinkedList<LabelDTO> getAllLabels() {
		List<Label> all = Label.getAll();
		LinkedList<LabelDTO> rslt = new LinkedList<LabelDTO>();
		for (Label la : all) {
			rslt.add(new LabelDTO(la.getID(), la.getName()));
		}
		return rslt;
	}

	@Override
	public String getAccessToAddQuestions() {
		Long UserID = (Long) this.getThreadLocalRequest().getSession()
				.getAttribute("user");
		if (UserID == null) {
			return "nul";
		}
		User u = User.getUser(UserID);
		//@FIXME here
		int rank = /*u.getRank();*/ 2;
		if (rank >= 2) {
			return u.getName();
		} else {
			return "nul";
		}
	}

	@Override
	public InfoDTO getQuestionByID(Long ID) {
		Question q = Question.getByID(ID);
		if (q==null){
			return null;
		}
		System.out.println("ок1");
		InfoDTO info = new InfoDTO(q.getQuestion(), q.getAnswer(), q.getLabelsNames(),
				q.getAuthorName(), q.getType(), q.getDuration(),
				q.getProvider());
		System.out.println("ок2");
		return info;
	}

}
